package producer.config;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @ClassName ZKConfig
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2022/1/11 上午12:19
 * @Version V1.0
 * @Since JDK 11
 */
public class ZKConfig {

    public static CuratorFramework client;

    static {
        client = client();
        client.start();
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            client.close();
        }));
    }

    private static CuratorFramework client() {
        Properties properties = new Properties();
        try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("zk-config.properties")) {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = properties.getProperty("url");
        String sessionTimeout = properties.getProperty("sessionTimeout","60000");
        String connectionTimeout = properties.getProperty("connectionTimeout","15000");
        return CuratorFrameworkFactory.builder()
                .connectString(url).sessionTimeoutMs(Integer.parseInt(sessionTimeout))
                .connectionTimeoutMs(Integer.parseInt(connectionTimeout))
                .namespace("my-rpc").retryPolicy(new ExponentialBackoffRetry(10000,5)).build();
    }
}
